package com.cj.myblog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cj.myblog.constants.Constants;
import com.cj.myblog.common.util.PageUtil;
import com.cj.myblog.common.util.SendMail;
import com.cj.myblog.dao.CommentRepository;
import com.cj.myblog.model.CommentDo;
import com.cj.myblog.model.PageBean;
import com.cj.myblog.service.CommentService;
import com.xiaoleilu.hutool.http.HtmlUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.util.ClassUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.ThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jujunchen on 2017/9/16.
 */
@Service
public class CommentServiceImpl implements CommentService{

    @Autowired
    private CommentRepository commentRepository;


    @Override
    public List<CommentDo> frontFindByArtId(Long id) {

        List<CommentDo> commentList = commentRepository.findByArtId(id);

        List<CommentDo> commentDos = commentRepository.findByArtIdHasCommentId(id);

        for (int i=0;i<commentList.size();i++){

            CommentDo commentDo = commentList.get(i);

            commentDo.setAvatar(getRandomAvatar());

            List<CommentDo> commentDoList = new ArrayList<>();

            for (CommentDo Do : commentDos){

                if (commentDo.getId().equals(Do.getCommentId())){
                    Do.setAvatar(getRandomAvatar());
                    commentDoList.add(Do);
                }

            }

            commentDo.setCommentDos(commentDoList);
        }

        return commentList;
    }

    private String getRandomAvatar(){
        int random = RandomUtil.randomInt(20);
        String path = "/theme/"+Constants.options.get("theme") + "/static/image/avatar/" + random +".png";
        boolean flag = FileUtil.exist(ClassUtil.getClassPath()+"templates/front"+path);
        if (flag){
            return path;
        }else {
           return path.replace(Constants.options.get("theme").toString(),Constants.THEME);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(CommentDo commentDo) {
        String facePath = ClassUtil.getClassPath()+"templates/front/theme/"+Constants.options.get("theme")+"/static/js/face.json";

        commentDo.setComment(HtmlUtil.filter(commentDo.getComment()));

        if (Constants.face.size() == 0){
            boolean isExist = FileUtil.exist(facePath);

            if (!isExist){
                facePath = facePath.replace(Constants.options.get("theme").toString(),"default");
            }
            String faceJson = FileUtil.readString(facePath,"utf-8");
            Constants.face = JSONObject.parseArray(faceJson,Map.class);
        }

        String comment = commentDo.getComment();

        for (Map map:Constants.face) {
            comment = comment.replace("["+String.valueOf(map.get("faceName"))+"]","<img src=\"/theme/"+Constants.options.get("theme")+String.valueOf(map.get("facePath"))+"\"/>");

        }

        commentDo.setComment(comment);

        commentRepository.save(commentDo);
        if (commentDo.getCommentId() != null && commentDo.getSendMail() == 1){
            Map<String,String> map = new HashMap<>();
            map.put("to",commentDo.getToUser());
            map.put("subject","您在《"+Constants.options.get("title")+"》的评论有最新回复啦！");
            map.put("url",Constants.options.get("url")+"/view/"+commentDo.getArtId()+"#"+commentDo.getToName()+commentDo.getCommentId());
            ThreadUtil.execute(new SendMail(map));
        }
    }


    @Override
    public PageBean<CommentDo> findAll(CommentDo commentDo) {

        Page<CommentDo> list = null;

        Pageable pageable = PageUtil.buildPageRequest(commentDo.getStart(),commentDo.getLength(),"createTime");


        list = commentRepository.findCommentDef(pageable);

        return new PageBean<>(list);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        commentRepository.delete(id);
    }

    @Override
    public CommentDo findOneById(Long id) {
       CommentDo commentDo =  commentRepository.findOne(id);
        return commentDo;
    }


}
